from flask import Blueprint, jsonify, request, current_app, url_for, send_from_directory
import os
import traceback
from datetime import datetime
from pathlib import Path
from app.server.lstm_model import LSTMForecaster

evaluate_lstm_bp = Blueprint('evaluate_lstm', __name__)

@evaluate_lstm_bp.route('/evaluate_lstm', methods=['GET'])
def lstm_evaluate():
    try:
        # 从配置获取模型路径
        model_dir = current_app.config.get('LSTM_MODEL_DIR', 'app/saved_models/LSTM')

        # 构建模型权重路径
        weights_path = os.path.join(model_dir, 'best_model.h5')

        # 检查模型文件是否存在
        if not os.path.exists(weights_path):
            return jsonify({
                'status': 'error',
                'message': f'模型文件不存在: {weights_path}'
            }), 404

        # 初始化预测器
        forecaster = LSTMForecaster(target_col='guilin_temp')

        # 加载模型和数据
        forecaster.train_test_split(test_size=0.2)
        forecaster.load_model(weights_path)

        # 执行评估（让模型决定结果路径）
        result = forecaster.evaluate()

        # 处理评估结果中的图表路径
        plot_path = result['plot_path']

        # 移除app\前缀（如果存在）
        if plot_path.startswith('app\\'):
            plot_path = plot_path[4:]  # 移除"app\"长度为4的前缀
        elif plot_path.startswith('app/'):
            plot_path = plot_path[4:]  # 处理可能的正斜杠情况

        print(f'plot_path:{plot_path}')
        # 构造响应
        response = {
            'status': 'success',
            'metrics': {
                'MAE': result['metrics']["MAE"],
                'R2': result['metrics']["R2"],
                'RMSE': result['metrics']["RMSE"],
            },
            'plot_url': plot_path,
            'model_type': 'LSTM'
        }

        return jsonify(response)

    except Exception as e:
        current_app.logger.error(f"LSTM评估失败: {traceback.format_exc()}")
        return jsonify({
            'status': 'error',
            'message': str(e),
            'details': traceback.format_exc() if current_app.debug else None
        }), 500